package com.example.ercmssystem2.service.impl;

import com.example.ercmssystem2.entity.Notification;
import com.example.ercmssystem2.entity.Event;
import com.example.ercmssystem2.entity.User;
import com.example.ercmssystem2.repository.NotificationRepository;
import com.example.ercmssystem2.service.NotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class NotificationServiceImpl implements NotificationService {

    @Autowired
    private NotificationRepository notificationRepository;

    @Override
    public Notification createNotification(User user, Event event, String title, String message, String type) {
        Notification notification = new Notification(user, event, title, message, type);
        return notificationRepository.save(notification);
    }

    @Override
    public Notification createSystemNotification(User user, String title, String message) {
        return createNotification(user, null, title, message, "SYSTEM");
    }

    @Override
    public Notification createEventNotification(User user, Event event, String title, String message, String type) {
        return createNotification(user, event, title, message, type);
    }

    @Override
    public List<Notification> createBatchNotifications(List<User> users, Event event, String title, String message, String type) {
        List<Notification> notifications = new ArrayList<>();
        for (User user : users) {
            Notification notification = createNotification(user, event, title, message, type);
            notifications.add(notification);
        }
        return notifications;
    }

    @Override
    public List<Notification> getUserNotifications(Long userId) {
        return notificationRepository.findByUserIdOrderByCreatedAtDesc(userId);
    }

    @Override
    public List<Notification> getUserUnreadNotifications(Long userId) {
        return notificationRepository.findByUserIdAndReadOrderByCreatedAtDesc(userId, false);
    }

    @Override
    public Long getUnreadCount(Long userId) {
        return notificationRepository.countUnreadByUserId(userId);
    }

    @Override
    public Notification markAsRead(Long notificationId) {
        Notification notification = notificationRepository.findById(notificationId).orElse(null);
        if (notification != null) {
            notification.markAsRead();
            return notificationRepository.save(notification);
        }
        return null;
    }

    @Override
    public void markAllAsRead(Long userId) {
        notificationRepository.markAllAsReadByUserId(userId, LocalDateTime.now());
    }

    @Override
    public void deleteNotification(Long notificationId) {
        notificationRepository.deleteById(notificationId);
    }

    @Override
    public void deleteOldNotifications(int daysOld) {
        LocalDateTime beforeDate = LocalDateTime.now().minusDays(daysOld);
        notificationRepository.deleteOldNotifications(beforeDate);
    }

    @Override
    public void sendRealTimeNotification(User user, String message) {
        // TODO: 实现WebSocket实时推送
        System.out.println("实时通知发送给用户 " + user.getUsername() + ": " + message);
    }

    @Override
    public void sendAssignmentNotification(Event event, User handler) {
        if (handler != null) {
            String title = "事件指派通知";
            String message = String.format("您已被指派处理事件：%s（ID：%d）", event.getTitle(), event.getId());
            createEventNotification(handler, event, title, message, "ASSIGNMENT");
            
            // 发送实时通知
            sendRealTimeNotification(handler, message);
        }
    }

    @Override
    public void sendProgressNotification(Event event, String progress) {
        // 通知事件报告人
        if (event.getReporter() != null) {
            String title = "事件进度更新";
            String message = String.format("您报告的事件：%s 进度已更新：%s", event.getTitle(), progress);
            createEventNotification(event.getReporter(), event, title, message, "PROGRESS");
        }
        
        // 通知调度员（这里可以扩展为通知所有调度员）
        // TODO: 获取所有调度员并发送通知
    }

    @Override
    public void sendEscalationNotification(Event event, String reason) {
        // 通知管理员
        // TODO: 获取所有管理员并发送升级通知
        String title = "事件升级通知";
        String message = String.format("事件：%s（ID：%d）已升级，原因：%s", event.getTitle(), event.getId(), reason);
        
        // 这里可以扩展为通知特定角色的人员
        System.out.println("升级通知: " + message);
    }
} 